package com.woniuxy.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import com.woniuxy.util.ResultVO;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gaopeng
 * @create 2020/04/2020/4/9 16:17:29
 */
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {
    // 只要sentinel抛出异常，都会被这里捕获！
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {

        response.setContentType("application/json;charset=utf-8");

        ResultVO r = null;
        if(e instanceof FlowException) {
            r = new ResultVO(-1, "接口被限流了");
        } else if(e instanceof DegradeException) {
            r = new ResultVO(-2, "接口降级流了");
        }
        response.getWriter().write(JSON.toJSONString(r));

    }
}
